package com.hong.utils.executors;

import java.util.concurrent.*;

/**
 * @Auther: Administrator
 * @Date: 2018/7/27 22:22
 * @Description:
 */
public class FutureExample1 {
    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
       /* ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) Executors.newCachedThreadPool();

        Future<?> future = threadPoolExecutor.submit(() -> {
            try {
                TimeUnit.SECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            return 10;
        });

        //===================================
        System.out.println("===========i will be printed quickly.");
        //===================================
        Thread callerhread = Thread.currentThread();
        new Thread(()->{
            try {
                TimeUnit.MILLISECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            callerhread.interrupt();
        }).start();
        Integer result = (Integer)future.get();
        System.out.println(result);*/

        testGetWithTimeOut();
    }

    /**
     *
     * @throws InterruptedException
     * @throws ExecutionException
     * @throws TimeoutException
     */
    private static void testGetWithTimeOut() throws InterruptedException, ExecutionException, TimeoutException {
        ExecutorService executorService = Executors.newCachedThreadPool();

        Future<Integer> future = executorService.submit(() -> {
            try {
                TimeUnit.SECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return 10;
        });
        Integer integer = future.get(5, TimeUnit.SECONDS);
        System.out.println(integer);
    }
}
